package com.heima.search.listener;

import com.alibaba.fastjson.JSON;
import com.heima.common.constants.ArticleConstants;
import com.heima.model.search.pojos.SearchArticleVo;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @author Xxx
 */
@Component
@Slf4j
public class SyncEsListener {
    @Autowired
    private RestHighLevelClient client;

    @KafkaListener(topics = ArticleConstants.TOPIC_SYNC_TO_ES)
    public void onMessage(String message) throws IOException {
        log.info("接收到同步消息：{}", message);
        SearchArticleVo searchArticleVo = JSON.parseObject(message, SearchArticleVo.class);
        IndexRequest indexRequest = new IndexRequest("app_info_article");
        indexRequest.id(searchArticleVo.getId() + "").source(message, XContentType.JSON);
        client.index(indexRequest, RequestOptions.DEFAULT);
    }
}
